<?php
/**
* @filename course_note.php 2016-9-6 02:10:56x
* @author Yunfent Zhang <306232452@qq.com>
* @version 1.0.0
* @copyright DZF (c) 2016, Yunfeng Zhang
*/
if(!defined('IN_SITE')) {
	exit('Access Denied');
}
class questions_answer{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
    public static $field_value=array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
	/*
	*	获取一条信息
	*/
	public function one_info($table_name,$key_name,$key_id='') {
		$info = array();
		if($table_name && $key_name && $key_id){
			$sql = "SELECT * FROM ".DB::table($table_name)." WHERE ".$key_name."='".$key_id."' LIMIT 1";
			$info = DB::fetch_first($sql);	
		}
		return $info;
	}
    
	/*
	*  添加信息
	*/
	public function add($table_name,$insert_data=array()) {		
        $insert_id = '';        
        if($table_name && $insert_data){
            $insert_id = DB::insert($table_name,$insert_data,true);
        }
        //插入问题表最后回复人
        if($insert_id){
        	$where = array('q_id'=>$insert_data['q_id']);        	
        	$sql = "SELECT * FROM ".DB::table('questions')." WHERE q_id = '".$insert_data['q_id']."' ";
        	$info = DB::fetch_first($sql);
        	
        	$update_data=array(
        			'end_reply_uid'=>$insert_data['user_id'],
        			'end_reply_time'=>TIMESTAMP,
        			'answer_num'   =>$info['answer_num']+1 //回答人数加1
        	);
        	
        	DB::update('questions',$update_data,$where);
        }
        return $insert_id;
	}
    
	/*
	*  编辑信息
	*/
	public function edit($table_name,$update_data,$where) {
        //DEBUG 定义返回 消息格式与消息代码编号
        $effect_row='';
        if($update_data && $where){
            $effect_row = DB::update($table_name,$update_data,$where);
        }
        return $effect_row;
	}
    
	/*
	*  删除信息
	*/
	public function delete($table_name,$where) {
        $return='';
        if($table_name && $where){
            $return = DB::delete($table_name, $where, $limit=1);
            //TODO 逻辑删需要创建isdelete字段 0=未删除 1=已删除
            //DB::update($table_name,array('isdelete'=>1), $table_name, $limit=1);
        }
        return $return;
    }
	/*
	*  问答信息
    *
    * @param $table_name string.
    * @param $page_condition array.
    *
    * @return array
	*/
	public function index($table_name,$page_condition){
		global $_G;
        $page_result = $answers_array = $result_data = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start=(($page-1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT * FROM ".DB::table($table_name)." WHERE 1=1 ".$wheresql." ".$page_condition['orderby']." ".DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM ".DB::table($table_name)." WHERE 1=1 ".$wheresql."";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        
        if($sql_info_result){
        	foreach ($sql_info_result as $key=>$val){
        		$result['questions']['id']=$val['q_id'];
        		$result['questions']['content']=$val['content'];
        		
        		$sql_info = "SELECT cm_name FROM ".DB::table('course_main')." WHERE cm_id = ".$val['cm_id'];        		
        		$course = DB::fetch_first($sql_info);
        		
        		$sql_info = "SELECT ud.user_nickname,u.user_name FROM ".DB::table('user_detail')." ud
        					LEFT JOIN " . DB::table('user') . "  u ON u.user_id = ud.user_id
        					WHERE ud.user_id = ".$val['user_id'];
        					
        		$user= DB::fetch_first($sql_info);
        		
        		$result['questions']['course']=$course['cm_name'];
        		$result['questions']['time']=date('Y-m-d H:i:s',$val['dateline']);
        		$result['questions']['name']=$user['user_nickname']?$user['user_nickname']:$user['user_name'];
        		if($_G['user_id']==$val['user_id']){
        			$result['questions']['is_asker']=1;
        		}else{
        			$result['questions']['is_asker']=0;
        		}
        		$sql_info = "SELECT * FROM ".DB::table('answers')." WHERE q_id = ".$val['q_id']." order by a_id DESC";
        		
        		$answers = DB::fetch_all($sql_info);
        		if($answers){
	        		foreach ($answers as $a_key=>$a_val){
	        			$answers_array['id']=$a_val['a_id'];
	        			$answers_array['content']=$a_val['content'];
	        			
	        			$sql_info = "SELECT ud.user_nickname,u.user_name FROM ".DB::table('user_detail')." ud
		        					LEFT JOIN " . DB::table('user') . "  u ON u.user_id = ud.user_id
		        					WHERE ud.user_id = ".$a_val['user_id'];
	        			//$sql_info = "SELECT user_name FROM ".DB::table('user')." WHERE user_id = ".$a_val['user_id'];
	        			$a_user = DB::fetch_first($sql_info);
	        			
	        			$answers_array['name']=$a_user['user_nickname']?$a_user['user_nickname']:$a_user['user_name'];
	        			$answers_array['time']=date('Y-m-d H:i:s',$a_val['dateline']);
	        			
	        			
	        		}
        		}
        		$result['answers'][] = $answers_array;
        		$result_data[]=$result;
        		
        	}
        }
        //DEBUG 列表数据返回结构
        $page_result = array(
            'page_now'=>$page,
            'total_page'=>max(1, ceil($sql_total_rows_result/$perpage)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $result_data 
        );
        return $page_result;
	}

	
	/*
	 *  获取回答信息
	 *
	 *
	 */
	public function get_answers($table_name,$page_condition){
		global $_G;
		$page_result = $info_answers = $q_array = $answers_array = $result_data = array();
		$page = $page_condition['page'];
		$limit = $page_condition['limit'];
		$perpage = $page_condition['perpage'];
		$start=(($page-1) * $perpage);
		$wheresql = $page_condition['wheresql'];
		$orderby = $page_condition['orderby'];
		$user_id = $page_condition['user_id'];
		$only_me = $page_condition['only_me'];
		$sql = "SELECT q_id FROM ".DB::table($table_name)." WHERE 1=1 ".$wheresql." ".$page_condition['orderby']." ".DB::limit($start, $limit);
		$info_answers = DB::fetch_all($sql);
		if($info_answers){
			foreach ($info_answers as $a_key=>$a_val){
				$q_array[]=$a_val['q_id'];
			}
		}
		$q_ids=array_unique($q_array);
	
		if($q_ids){
			foreach ($q_ids as $q_key=>$q_val){
				$sql = "SELECT * FROM ".DB::table('questions')." WHERE q_id = ".$q_val;
				$info_question = DB::fetch_first($sql);
				
				$result['questions']['id']=$info_question['q_id'];
				$result['questions']['content']=$info_question['content'];
	
				$sql_info = "SELECT cm_name FROM ".DB::table('course_main')." WHERE cm_id = ".$info_question['cm_id'];
				$course = DB::fetch_first($sql_info);
	
				$sql_info = "SELECT ud.user_nickname,u.user_name FROM ".DB::table('user_detail')." ud
        					LEFT JOIN " . DB::table('user') . "  u ON u.user_id = ud.user_id
        					WHERE ud.user_id = ".$info_question['user_id'];
				 
				$user= DB::fetch_first($sql_info);
	
				$result['questions']['course']=$course['cm_name'];
				$result['questions']['time']=date('Y-m-d H:i:s',$info_question['dateline']);
				$result['questions']['name']=$user['user_nickname']?$user['user_nickname']:$user['user_name'];
				if($_G['user_id']==$info_question['user_id']){
					$result['questions']['is_asker']=1;
				}else{
					$result['questions']['is_asker']=0;
				}
				if($user_id && $only_me ==1){
					$sql_info = "SELECT * FROM ".DB::table('answers')." WHERE q_id = ".$info_question['q_id']." and user_id = ".$user_id." order by a_id DESC";
				}else{				
					$sql_info = "SELECT * FROM ".DB::table('answers')." WHERE q_id = ".$info_question['q_id']." order by a_id DESC";
				}
				$answers = DB::fetch_all($sql_info);
				if($answers){
					foreach ($answers as $a_key=>$a_val){
						$answers_array['id']=$a_val['a_id'];
						$answers_array['content']=$a_val['content'];
	
						$sql_info = "SELECT ud.user_nickname,u.user_name FROM ".DB::table('user_detail')." ud
		        					LEFT JOIN " . DB::table('user') . "  u ON u.user_id = ud.user_id
		        					WHERE ud.user_id = ".$a_val['user_id'];
						//$sql_info = "SELECT user_name FROM ".DB::table('user')." WHERE user_id = ".$a_val['user_id'];
						$a_user = DB::fetch_first($sql_info);
	
						$answers_array['name']=$a_user['user_nickname']?$a_user['user_nickname']:$a_user['user_name'];
						$answers_array['time']=date('Y-m-d H:i:s',$a_val['dateline']);
	
	
					}
				}
				$result['answers'][] = $answers_array;
				$result_data[]=$result;
	
			}
		}			
		return $result_data;
	}
   /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */
	public function api($table_name,$page_condition){
        $page_result = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start=(($page-1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT * FROM ".DB::table($table_name)." WHERE 1=1 ".$wheresql." ".$page_condition['orderby']." ".DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM ".DB::table($table_name)." WHERE 1=1 ".$wheresql."";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        //DEBUG 列表数据返回结构
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result 
        );
        return $page_result;
	}

    /*
	*  获取表字段值
    * @param $table_name string
    * @param $key_name string
    * @param $key_id string/array
    * @param $field_name array
    *
    * @return $field_value array
	*/    
    protected static function get_field_value_by_id($table_name,$key_name,$key_id,$field_name) {
		if(is_array($key_id) && !empty($key_id)){
			$key_ids = implode('_',$key_id);
			if(!isset(self::$field_value[$field_name][$key_ids])) {
				$return = DB::fetch_all('SELECT '.$key_name.','.$field_name.' FROM '.DB::table($table_name)." WHERE ".$key_name." IN (".dimplode($key_id).")");
				foreach($return AS $key => $value){
					$return_tmp[$value[$key_name]] = $value[$field_name];
					unset($return[$key]);
				}
				self::$field_value[$field_name][$key_ids]=$return_tmp;
				$key_id = $key_ids;
			}else{
				$key_id = $key_ids;
			}
		}else{
			if(!isset(self::$field_value[$field_name][$key_id])) {
				self::$field_value[$field_name][$key_id]=DB::result_first('SELECT '.$field_name.' FROM '.DB::table($table_name)." WHERE ".$key_name."='".$key_id."' LIMIT 1");
			}
		}
		return self::$field_value[$field_name][$key_id];
	}
    
	/*
	* ajax 返回信息
	*/
	public function return_json($error,$message,$output=1) {
		$return_array = array(
			"error" => $error,
			"message" => $message
		);
		if($output){
			echo json_ext($return_array);
			die;
		}else{
			return json_ext($return_array);
		}
	}
}
?>